package bootstrap

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"context"
	"fmt"

	"github.com/k8gb-io/k8gb/controllers/resolver"

	netv1 "k8s.io/api/networking/v1"

	"github.com/k8gb-io/k8gb/controllers/providers/assistant"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/client-go/rest"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

type Bootstrap struct {
	source corev1.ServiceType
	svc    *corev1.Service
	ing    *netv1.Ingress
	IPs    []string
	Name   string
}

func GetBootstrap(ctx context.Context, config *resolver.Config, kubeconfig *rest.Config) (*Bootstrap, error) {
	cl, err := client.New(kubeconfig, client.Options{})
	if err != nil {
		return nil, err
	}
	return GetBootstrapWithClient(ctx, config, cl)
}

func GetBootstrapWithClient(ctx context.Context, config *resolver.Config, cl client.Client) (*Bootstrap, error) {
	bootstrap, err := readIPs(ctx, cl, config)
	if err != nil {
		return nil, err
	}
	if len(bootstrap.IPs) == 0 {
		return nil, fmt.Errorf("no IP addresses found")
	}
	return bootstrap, nil
}

func readIPs(ctx context.Context, cl client.Client, config *resolver.Config) (*Bootstrap, error) {
	var err error
	boot := &Bootstrap{source: config.CoreDNSServiceType}
	if boot.HasIngress() {
		ingresAssistant := assistant.NewIngressAssistant(ctx, cl)
		boot.IPs, boot.ing, err = ingresAssistant.GetExposedIPs()
		return boot, err
	}
	coreDNSAssistant := assistant.NewCoreDNSServiceAssistant(ctx, cl, *config)
	boot.IPs, boot.svc, err = coreDNSAssistant.GetExposedIPs()
	return boot, err
}

func (b *Bootstrap) HasIngress() bool {
	return b.source != corev1.ServiceTypeLoadBalancer
}

func (b *Bootstrap) String() string {
	if b.HasIngress() {
		return fmt.Sprintf("Ingress %s/%s %s", b.ing.Namespace, b.ing.Name, b.IPs)
	}
	return fmt.Sprintf("Service type LoadBalancer %s/%s %s", b.svc.Namespace, b.svc.Name, b.IPs)
}
